//
//  Tabbar+Extension.swift
//  SwiftExercise
//
//  Created by 罗宗庆 on 2021/6/24.
//

import Foundation

extension UITabBar{
    
    func addLottieImage(index:NSInteger, lottieImage:String){
        if Thread.isMainThread {
            self.addLottieImageInMainThread(index: index, lottieName: lottieImage)
        }else{
            DispatchQueue.main.async {
                self.addLottieImageInMainThread(index: index, lottieName: lottieImage)
            }
        }
    }
    
    func addLottieImageInMainThread(index:NSInteger,lottieName:String){
        let lottieView = LOTAnimationView()
        lottieView.setAnimation(named: lottieName)
        let totalW = UIScreen.main.bounds.width
        let singleW = Double(totalW) / Double(self.items!.count)
        
        let x = ceilf(Float(CGFloat(Double(index) * singleW) + CGFloat((singleW - Double(LOTAnimationViewWidth)) / 2.0)))
        let y = 0
        lottieView.frame = CGRect(x: Int(x), y: y, width: LOTAnimationViewWidth, height: LOTAnimationViewHeight)
        lottieView.isUserInteractionEnabled = true
        lottieView.contentMode = .scaleAspectFit
        lottieView.tag = 888 + index
        self.addSubview(lottieView)
    }
    
    func animationLottieImage(index:NSInteger){
        self.stopAnimationAllLottieView()
        let lottieView:LOTAnimationView = self.viewWithTag(888+index) as! LOTAnimationView
        lottieView.animationProgress = 0
        lottieView.play()
    }
    
    func stopAnimationAllLottieView(){
        for i in 0..<self.items!.count{
            let lottieView:LOTAnimationView = self.viewWithTag(888+i) as! LOTAnimationView
             lottieView.stop()
        }
    }
    
}
